package com.java.mail.receiver;

import org.javaboy.vhr.model.Employee;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.mail.MailProperties;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.Date;

@Component
public class MailReceiver {
    @Autowired
    JavaMailSender javaMailSender;
    @Autowired
    MailProperties mailProperties;
    @Autowired
    TemplateEngine templateEngine;
    @RabbitListener(queues="start-work-welcome")
    public void sendMailHandler(Employee employee){
        // 注意:Employee 类需要序列化,所以才搞成多模块 相当于使用同一个类
        System.out.println("rabbitmq发布成功");
        MimeMessage message = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message);
        try {
            // 谁发的
            helper.setFrom(mailProperties.getUsername());
            // 发给谁
            helper.setTo("15238096756@163.com");
            // 主题
            helper.setSubject("入职欢迎");
            // 日期
            helper.setSentDate(new Date());

            // 模板信息处理渲染(Thymeleaf)
            Context context = new Context();
            context.setVariable("name",employee.getName());
            context.setVariable("department",employee.getDepartment().getName());
            context.setVariable("workId",employee.getWorkId());
            String text = templateEngine.process("startWorkWelcome", context);
            helper.setText(text,true);
            // 发送
            javaMailSender.send(message);
        } catch (MessagingException e) {
            e.printStackTrace();
        }
        System.out.println("发送邮件");
    }
}
